/**
 * Created by wry on 2015/5/14.
 */

var async = require('async');
var Users = mongoose.model('user');
var inviteRecord = mongoose.model('invite_score_record');
var moment = require('moment');
var deviceCodeBind = mongoose.model('relation_deviceCodeBind');
var toolUtil = require('./toolUtil');

exports.query = function (sql, values, callback) {
    mysqlPool.getConnection(function (err, connection) {
        if (err) throw err;
        if (typeof values == 'function') {
            connection.query(sql, function (err, rows) {
                connection.release();
                values(err, rows);
            });
        } else {
            connection.query(sql, values, function (err, rows) {
                connection.release();
                callback(err, rows);
            });
        }
    });
};


exports.logQuery = function (sql, values, callback) {
    mysqlLogPool.getConnection(function (err, connection) {
        if (err) throw err;
        if (typeof values == 'function') {
            connection.query(sql, function (err, rows) {
                connection.release();
                values(err, rows);
            });
        } else {
            connection.query(sql, values, function (err, rows) {
                connection.release();
                callback(err, rows);
            });
        }
    });
};

exports.recQuery = function (sql, values, callback) {
    mysqlRecPool.getConnection(function (err, connection) {
        if (err) throw err;
        if (typeof values == 'function') {
            connection.query(sql, function (err, rows) {
                connection.release();
                values(err, rows);
            });
        } else {
            connection.query(sql, values, function (err, rows) {
                connection.release();
                callback(err, rows);
            });
        }
    });
};


/**
 * 生成代金券
 */
exports.generateUserVoucher = function (userId, rewardSource, invited, callback) {

    deviceCodeBind.findOne({user: invited}, function (err, bind) {
        if (bind != null) {
            deviceCodeBind.findOne({deviceId: bind.deviceId, status: true}, function (err, status) {
                if (status == null) {
                    Users.findOne({_id: userId}, function (err, user) {
                        if (user == null || user.community == null) {
                            callback({message: '无效用户'})
                        } else {

                            inviteRecord.findOne({
                                user: userId + '',
                                invited: invited
                            }, function (err, invite) {
                                if (invite == null) {
                                    Users.findOne({_id: invited}, 'nickName', function (err, temp) {

                                        toolUtil.hessianManualAddScore(userId + '', 11, INVITE_SCORE, '成功邀请' + temp.nickName, function (err, value) {
                                            if (value != null) {
                                                var record = new inviteRecord();
                                                record.user = userId + '';
                                                record.invited = invited;
                                                record.source = 2;
                                                record.score = INVITE_SCORE;
                                                record.reason = '成功邀请' + temp.nickName;
                                                record.save();

                                                deviceCodeBind.update({
                                                    user: invited,
                                                    deviceId: bind.deviceId
                                                }, {status: true}, {multi: true}).exec();
                                            }
                                            callback(null, {
                                                value: INVITE_SCORE,
                                                type: 1
                                            });
                                        });
                                    });
                                } else {
                                    callback({message: '无法重复增加奖励'})
                                }
                            });

                            //exports.query('select * from voucher_user_bind where user_id=? and invited_user=? and reward_source=?', [userId + '', invited, rewardSource], function (err, result) {
                            //    if (err || result.length > 0) {
                            //        if (err)logger.error(err.message);
                            //        callback({message: '无法重复增加奖励'})
                            //    } else {
                            //        var community = user.community + '';
                            //        var nowDate = new Date().getTime();
                            //        var sql = 'select voucher_type_id,reward_expiredate_length,type,voucher_val,community_name from voucher_reward_rule r,voucher_type t where r.from_time<? and r.to_time>? and r.reward_source=? and r.community_id=? and t.id=r.voucher_type_id';
                            //        exports.query(sql, [nowDate, nowDate, rewardSource, community], function (err, result) {
                            //            if (err || result.length == 0) {
                            //                logger.error(err ? err : '无奖励规则');
                            //                callback({message: '无奖励规则'});
                            //            } else {
                            //                if (result[0].type == 1) {
                            //                    exports.getCardNumber(function (number) {
                            //                        var cardNo = moment().format('YYMMDD') + number;
                            //                        var expire = moment(nowDate).endOf('day').toDate().getTime() + result[0].reward_expiredate_length * 24 * 60 * 60 * 1000;
                            //                        var data = {
                            //                            user_id: userId + '',
                            //                            invited_user: invited,
                            //                            expire_time: expire,
                            //                            voucher_type_id: result[0].voucher_type_id,
                            //                            is_use: 0,
                            //                            reward_source: rewardSource,
                            //                            card_no: cardNo,
                            //                            community_name: result[0].community_name,
                            //                            create_time: new Date().getTime()
                            //                        };
                            //                        exports.query('insert into voucher_user_bind set?', data, function (err, vou) {
                            //                            if (!err) {
                            //                                deviceCodeBind.update({
                            //                                    user: invited,
                            //                                    deviceId: bind.deviceId
                            //                                }, {status: true}, {multi: true}).exec();
                            //
                            //                                var content = {
                            //                                    type: 1,
                            //                                    flag: 2,
                            //                                    openType: 8,
                            //                                    contentId: userId,
                            //                                    desc: '恭喜您！您获得了一张代金券'
                            //                                };
                            //                                var pushData = {
                            //                                    uList: [userId],
                            //                                    content: content,
                            //                                    tag: '福利券',
                            //                                    type: 'operate'
                            //                                };
                            //                                toolUtil.putMessageGetuiPushMQ(pushData);
                            //                            }
                            //                            callback(err, {type: 2, value: result[0].voucher_val})
                            //                        })
                            //                    });
                            //                } else if (result[0].type == 2) {
                            //                }
                            //            }
                            //        });
                            //    }
                            //});
                        }
                    })
                } else {
                    callback({message: '设备无法重复增加奖励'})
                }
            })
        } else {
            callback({message: '无设备无法增加奖励'})
        }
    });
};

exports.getCardNumber = function (callback) {
    var key = 'voucher:card:no';
    redisClient.incr(key, function (err, value) {
        callback(value);
    })
};